<?php

namespace App\Console\Commands\OpenShop;

use App\Library\FeiShu\SendFs;
use App\Service\OpenShop\Organization\WarZoneService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use App\Service\SiteLocation\SiteLocationLogicService;
use Carbon\Carbon;
use Guanguans\Notify\Factory;
use Illuminate\Console\Command;
use Kuafu\GeneralFs\BuildFs;

class SiteRankingList extends Command
{

    const SITE_TYPE_OPEN_SHOP  = '确址';
    const SITE_TYPE_HOUSE_CLUE = '上架房源';

    const SITE_IMAGE_OPEN_SHOP  = 'img_v2_861bcade-287c-4441-abed-67b5fd73656g';
    const SITE_IMAGE_HOUSE_CLUE = 'img_v2_eb53d9bc-ac14-4889-9fdb-b24a92b3001g';

    const SITE_USER_TYPE_OWN     = 1; //专职开发团队
    const SITE_USER_TYPE_ANOTHER = 2; //兼职开发团队

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:site-ranking-list-notify';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '选址房源确址排行榜';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        GuanyuanDataService::setTimeOut(30);
        $siteOpenShopData = GuanyuanDataService::getSiteOpenShopData();
        //$siteHouseClueData = GuanyuanDataService::getSiteHouseClueData();
        //一个个去设置
        $totalOpenShop        = 0;
        $dataOpenShop         = [];
        $countOpenShop        = 0;
        $dataOpenShopAnother  = [];
        $countOpenShopAnother = 0;
        //$totalHouseClue = 0;
        //$dataHouseClue  = [];

        //开始统计的月份时间
        $initMonth = Carbon::now()->startOfMonth()->format('Y-m-d');
        $statisticsMonth = $initMonth;
        if ($initMonth == formatDateYmd(time())) {
            $statisticsMonth = Carbon::now()->subMonth()->startOfMonth()->format('Y-m-d');
        }
        foreach ($siteOpenShopData as $siteOpenShop) {
            if ($siteOpenShop['确址月份'] != $statisticsMonth) {
                continue;
            }
            $totalOpenShop += ($siteOpenShop['昨天新增确址门店数'] ?: 0);
            if ($siteOpenShop['选址人员类型'] == '专职开发团队') {
                $countOpenShop                                               += ($siteOpenShop['昨天新增确址门店数'] ?: 0);
                $dataOpenShop[$siteOpenShop['开发经理本名']]['name']         = $siteOpenShop['开发经理'];
                $dataOpenShop[$siteOpenShop['开发经理本名']]['department']   = $siteOpenShop['部门'];
                $dataOpenShop[$siteOpenShop['开发经理本名']]['option']       = $siteOpenShop['选址人员类型'];
                $dataOpenShop[$siteOpenShop['开发经理本名']]['recommend']    = ($dataOpenShop[$siteOpenShop['开发经理本名']]['recommend'] ?? 0) + ($siteOpenShop['选址类型聚合'] == '推荐址' ? ($siteOpenShop['本月确址门店数'] ?? 0) : 0);
                $dataOpenShop[$siteOpenShop['开发经理本名']]['recommendAdd'] = ($dataOpenShop[$siteOpenShop['开发经理本名']]['recommendAdd'] ?? 0) + ($siteOpenShop['选址类型聚合'] == '推荐址' ? ($siteOpenShop['昨天新增确址门店数'] ?: 0) : 0);
                $dataOpenShop[$siteOpenShop['开发经理本名']]['byo']          = ($dataOpenShop[$siteOpenShop['开发经理本名']]['byo'] ?? 0) + ($siteOpenShop['选址类型聚合'] == '自带址' ? ($siteOpenShop['本月确址门店数'] ?? 0) : 0);
                $dataOpenShop[$siteOpenShop['开发经理本名']]['byoAdd']       = ($dataOpenShop[$siteOpenShop['开发经理本名']]['byoAdd'] ?? 0) + ($siteOpenShop['选址类型聚合'] == '自带址' ? ($siteOpenShop['昨天新增确址门店数'] ?: 0) : 0);
                $dataOpenShop[$siteOpenShop['开发经理本名']]['total']        = ($dataOpenShop[$siteOpenShop['开发经理本名']]['total'] ?? 0) + ($siteOpenShop['本月确址门店数'] ?: 0);

            } else {
                $countOpenShopAnother                                               += ($siteOpenShop['昨天新增确址门店数'] ?: 0);
                $dataOpenShopAnother[$siteOpenShop['开发经理本名']]['name']         = $siteOpenShop['开发经理'];
                $dataOpenShopAnother[$siteOpenShop['开发经理本名']]['department']   = $siteOpenShop['部门'];
                $dataOpenShopAnother[$siteOpenShop['开发经理本名']]['option']       = $siteOpenShop['选址人员类型'];
                $dataOpenShopAnother[$siteOpenShop['开发经理本名']]['recommend']    = ($dataOpenShopAnother[$siteOpenShop['开发经理本名']]['recommend'] ?? 0) + ($siteOpenShop['选址类型聚合'] == '推荐址' ? ($siteOpenShop['本月确址门店数'] ?? 0) : 0);
                $dataOpenShopAnother[$siteOpenShop['开发经理本名']]['recommendAdd'] = ($dataOpenShopAnother[$siteOpenShop['开发经理本名']]['recommendAdd'] ?? 0) + ($siteOpenShop['选址类型聚合'] == '推荐址' ? ($siteOpenShop['昨天新增确址门店数'] ?: 0) : 0);
                $dataOpenShopAnother[$siteOpenShop['开发经理本名']]['byo']          = ($dataOpenShopAnother[$siteOpenShop['开发经理本名']]['byo'] ?? 0) + ($siteOpenShop['选址类型聚合'] == '自带址' ? ($siteOpenShop['本月确址门店数'] ?? 0) : 0);
                $dataOpenShopAnother[$siteOpenShop['开发经理本名']]['byoAdd']       = ($dataOpenShopAnother[$siteOpenShop['开发经理本名']]['byoAdd'] ?? 0) + ($siteOpenShop['选址类型聚合'] == '自带址' ? ($siteOpenShop['昨天新增确址门店数'] ?: 0) : 0);
                $dataOpenShopAnother[$siteOpenShop['开发经理本名']]['total']        = ($dataOpenShopAnother[$siteOpenShop['开发经理本名']]['total'] ?? 0) + ($siteOpenShop['本月确址门店数'] ?: 0);

            }
        }
        //        foreach ($siteHouseClueData as $siteHouseClue) {
        //            if ($siteHouseClue['房源上架月份'] != Carbon::now()->startOfMonth()->format('Y-m-d')) {
        //                continue;
        //            }
        //            $totalHouseClue                                               = $totalHouseClue + ($siteHouseClue['昨天新增房源数'] ?: 0);
        //            $dataHouseClue[$siteHouseClue['开发经理本名']]['name']         = $siteHouseClue['开发经理'];
        //            $dataHouseClue[$siteHouseClue['开发经理本名']]['department']   = $siteHouseClue['部门'];
        //            $dataHouseClue[$siteHouseClue['开发经理本名']]['recommend']    = ($dataHouseClue[$siteHouseClue['开发经理本名']]['recommend'] ?? 0) + ($siteHouseClue['选址类型聚合'] == '推荐址' ? ($siteHouseClue['本月累计房源数'] ?? 0) : 0);
        //            $dataHouseClue[$siteHouseClue['开发经理本名']]['recommendAdd'] = ($dataHouseClue[$siteHouseClue['开发经理本名']]['recommendAdd'] ?? 0) + ($siteHouseClue['选址类型聚合'] == '推荐址' ? ($siteHouseClue['昨天新增房源数'] ?: 0) : 0);
        //            $dataHouseClue[$siteHouseClue['开发经理本名']]['byo']          = ($dataHouseClue[$siteHouseClue['开发经理本名']]['byo'] ?? 0) + ($siteHouseClue['选址类型聚合'] == '自带址' ? ($siteHouseClue['本月累计房源数'] ?? 0) : 0);
        //            $dataHouseClue[$siteHouseClue['开发经理本名']]['byoAdd']       = ($dataHouseClue[$siteHouseClue['开发经理本名']]['byoAdd'] ?? 0) + ($siteHouseClue['选址类型聚合'] == '自带址' ? ($siteHouseClue['昨天新增房源数'] ?: 0) : 0);
        //            $dataHouseClue[$siteHouseClue['开发经理本名']]['total']        = ($dataHouseClue[$siteHouseClue['开发经理本名']]['total'] ?? 0) + ($siteHouseClue['本月累计房源数'] ?: 0);
        //        }
        // 为0的不过滤  选址
        //        foreach ($data as $k => $datum) {
        //            if ($datum['total'] == 0) {
        //                unset($data[$k]);
        //            }
        //        }
        $dataOpenShop        = collect($dataOpenShop)->sortByDesc('byo')->sortByDesc('recommend')->toArray();
        $dataOpenShopAnother = collect($dataOpenShopAnother)->sortByDesc('byo')->sortByDesc('recommend')->toArray();
        //$dataHouseClue = array_values(arraySort($dataHouseClue, 'total'));

        $year       = Carbon::now()->format('Y');
        $month      = Carbon::now()->format('m');
        $day        = Carbon::now()->format('d');
        $startMonth = Carbon::now()->startOfMonth()->format('m');

        if ($initMonth == formatDateYmd(time())) {
            if ($month == '01') {
                $year = Carbon::now()->subYear()->format('Y');
            }
            $month      = Carbon::now()->subMonth()->startOfMonth()->format('m');
            $startMonth = $month;
            $day        = Carbon::now()->subMonth()->endOfMonth()->format('d');
        }

        $json             = json_decode(
            sprintf(
                file_get_contents(resource_path('OpenShop/feishu/notifyTemplate/siteRankingList.json')),
                $year . '年' . $month . '月',
                $startMonth . '月01日',
                $month . '月' . $day . '日',
                $totalOpenShop
            ), true
        );
        $json['elements'] = array_merge($json['elements'], self::getCardJson($dataOpenShop, self::SITE_USER_TYPE_OWN, $countOpenShop), self::getCardJson($dataOpenShopAnother, self::SITE_USER_TYPE_ANOTHER, $countOpenShopAnother));
        if ('prod' == config('app.env')) {
            //选址培训群
            $robot = [
                'url'      => 'https://open.feishu.cn/open-apis/bot/v2/hook/2c7a9a24-1add-4962-98cc-aeba6cd9da92',
                'urlToken' => '2c7a9a24-1add-4962-98cc-aeba6cd9da92',
                'secret'   => '7cTNC4RZD7piOybT6yDJfe'
            ];

            // 生产环境开发群推送
            BuildFs::newRobot(SendFs::ROBOT_INTENDED_SITE_SELECTION_CONFIRM_DMG, BuildFs::MSG_TYPE_CARD)
                ->setCardContent($json)
                ->send();

        } else {
            //测试群
            $robot = [
                'url'      => 'https://open.feishu.cn/open-apis/bot/v2/hook/541b19a5-99ca-4d6f-a556-e07155e5d6cc',
                'urlToken' => '541b19a5-99ca-4d6f-a556-e07155e5d6cc',
                'secret'   => 'g4gt6l3sXrp3E04GkYH1Yg'
            ];
        }
        Factory::feiShu()
            ->setToken($robot['urlToken'])
            ->setSecret($robot['secret'])
            ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($json))
            ->send();

        try {
            // 战区推送
            if (config('app.env') == 'prod') {
                $robotConfig = SiteLocationLogicService::getRobotByRegionManageId(0);
                foreach ($robotConfig as $item) {
                    foreach ($item['robot'] as $robot) {
                        BuildFs::newRobot(0, BuildFs::MSG_TYPE_CARD)
                            ->setCardContent($json)
                            ->setRobotConfig($robot['url'], $robot['token'])
                            ->send();
                    }
                }
            }
        }catch (\Exception $exception) {}

        //        Factory::feiShu()
        //            ->setToken($robot['urlToken'])
        //            ->setSecret($robot['secret'])
        //            ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage(self::getCardJson($totalHouseClue, $dataHouseClue, self::SITE_TYPE_HOUSE_CLUE, self::SITE_IMAGE_HOUSE_CLUE)))
        //            ->send();
    }

    public static function getCardJson($data, $type, $total)
    {
        $json[] = [
            'tag' => 'hr'
        ];
        switch ($type) {
            case self::SITE_USER_TYPE_OWN:
                $json[] = [
                    'tag'  => 'div',
                    'text' => [
                        "content" => "**🌟🌟🌟专职开发团队🌟🌟🌟**\n昨日新增确址 " . $total . " 家",
                        "tag"     => "lark_md"
                    ],
                ];
                break;
            case self::SITE_USER_TYPE_ANOTHER:
                $json[] = [
                    'tag'  => 'div',
                    'text' => [
                        "content" => "**🌟🌟🌟兼职开发团队🌟🌟🌟**\n昨日新增确址 " . $total . " 家",
                        "tag"     => "lark_md"
                    ],
                ];
                break;
            default:

        }
        foreach (array_values($data) as $key => $value) {
            switch ($key) {
                case 0:
                    $json[] = [
                        'tag'  => 'div',
                        'text' => [
                            "content" => " 🥇 第1名：<font color='blue'>" . $value['name'] . "</font>@" . $value['department'] . "\n累计推荐址落位：" . $value['recommend'] . "家（昨日新增：" . $value['recommendAdd'] . "家）\n累计自带址落位：" . $value['byo'] . "家（昨日新增：" . $value['byoAdd'] . "家）",
                            "tag"     => "lark_md"
                        ],
                    ];
                    break;
                case 1:
                    $json[] = [
                        'tag'  => 'div',
                        'text' => [
                            "content" => " 🥈 第2名：<font color='blue'>" . $value['name'] . "</font>@" . $value['department'] . "\n累计推荐址落位：" . $value['recommend'] . "家（昨日新增：" . $value['recommendAdd'] . "家）\n累计自带址落位：" . $value['byo'] . "家（昨日新增：" . $value['byoAdd'] . "家）",
                            "tag"     => "lark_md"
                        ],
                    ];
                    break;
                case 2:
                    $json[] = [
                        'tag'  => 'div',
                        'text' => [
                            "content" => " 🥉 第3名：<font color='blue'>" . $value['name'] . "</font>@" . $value['department'] . "\n累计推荐址落位：" . $value['recommend'] . "家（昨日新增：" . $value['recommendAdd'] . "家）\n累计自带址落位：" . $value['byo'] . "家（昨日新增：" . $value['byoAdd'] . "家）",
                            "tag"     => "lark_md"
                        ],
                    ];
                    break;
                default:
                    $json[] = [
                        'tag'  => 'div',
                        'text' => [
                            "content" => " 第" . ($key + 1) . "名：<font color='blue'>" . $value['name'] . "</font>@" . $value['department'] . "\n累计推荐址落位：" . $value['recommend'] . "家（昨日新增：" . $value['recommendAdd'] . "家）\n累计自带址落位：" . $value['byo'] . "家（昨日新增：" . $value['byoAdd'] . "家）",
                            "tag"     => "lark_md"
                        ],
                    ];
            }

        }
        return $json;
    }
}
